import React from "react";
import { Button, Checkbox, Form, Input } from "antd";
import { useNavigate } from "react-router-dom";
import request from "../utils/request";

import { connect } from "react-redux";

function Login(props) {
    const navigate = useNavigate();

    const { login } = props;

    const onFinish = async (values) => {
        const { data } = await request.post("/manager/login", values);
        if (data.code === 200) {
            login(data.data);

            navigate("/manage");
        }
    };

    return (
        <div className="login">
            <h1>趣学藏书阁管理系统</h1>
            <Form
                name="basic"
                labelCol={{
                    span: 8,
                }}
                wrapperCol={{
                    span: 16,
                }}
                initialValues={{
                    remember: true,
                }}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Form.Item
                    label="管理者："
                    name="manager"
                    rules={[
                        {
                            required: true,
                            message: "请输入管理者用户名名",
                        },
                    ]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="密码："
                    name="password"
                    rules={[
                        {
                            required: true,
                            message: "请输入密码",
                        },
                    ]}
                >
                    <Input.Password />
                </Form.Item>

                <Form.Item
                    name="remember"
                    valuePropName="checked"
                    wrapperCol={{
                        offset: 8,
                        span: 16,
                    }}
                >
                    <Checkbox>记住我</Checkbox>
                </Form.Item>

                <Form.Item
                    wrapperCol={{
                        offset: 8,
                        span: 16,
                    }}
                >
                    <Button type="primary" htmlType="submit">
                        登录
                    </Button>
                </Form.Item>
            </Form>
        </div>
    );
}

Login = connect(
    (state) => {
        return {};
    },
    (dispatch) => {
        return {
            login(userInfo) {
                dispatch({ type: "login", payload: userInfo });
            },
        };
    }
)(Login);

export default Login;
